package com.gdk.ksoft.ui.logins;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.SaleManTable;
import com.gdk.ksoft.ui.MainActivity;
import com.gdk.ksoft.ui.mores.SoftwareSettingsActivity;
import com.gdk.ksoft.assembly.receiver.ExitAppReceiver;
import com.gdk.ksoft.assembly.service.ForegroundService;
import com.gdk.ksoft.assembly.service.LocationService;
import com.gdk.ksoft.assembly.utils.system.ConfigUtils;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.PhoneUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.assembly.utils.UpdateUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 登录页面
 */
public class LoginActivity extends Activity {

    /**
     * 密码标识字符串
     */
    public static final String PASSWORD_FIELD = "password";
    private static DbUtils dbUtils;//数据库操作类

    @ViewInject(R.id.plogin_txtTitle)
    private TextView txtTitle;//标题文字
    @ViewInject(R.id.plogin_imgFace)
    private ImageView imgFace;//用户头像
    @ViewInject(R.id.plogin_txtName)
    private TextView txtName;//用户名
    @ViewInject(R.id.plogin_etPassword)
    private EditText etPassword;//用户密码
    private SharedPreferences configer;//获取配置文件对象
    private ExitAppReceiver exitAppReceiver;//退出程序通知

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ViewUtils.inject(this);
        registeExitAppReceiver();//注册退出应用的通知
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        configer = ConfigUtils.getInstance(this).getSharedPreference();//初始化配置文件对象
        UpdateUtils.checkVersion(this,false);//检测更新
        initActivity();//初始化页面数据
    }

    /**
     * 初始化页面数据
     */
    public void initActivity(){
        try {
            if (!isNeedDownloadNewData()) initSaleManInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (configer.contains(PASSWORD_FIELD)) {//检测密码是否存在，如果存在则显示改密码
            String password = configer.getString(PASSWORD_FIELD, "");
            if (!TextUtils.isEmpty(password.trim())) {//如果密码不为空值，显示该密码
                etPassword.setText(password.trim());
            }
        }
    }


    /**
     * 注册退出应用的通知
     */
    public void registeExitAppReceiver(){
        exitAppReceiver = new ExitAppReceiver(new ExitAppReceiver.OnExitAppListener() {
            @Override
            public void onExitApp() {
                LoginActivity.this.goBack();
            }
        });
        IntentFilter filter = new IntentFilter(ExitAppReceiver.ACTION);
        this.registerReceiver(exitAppReceiver,filter);
    }

    /**
     * 初始化业务员信息
     */
    public void initSaleManInfo() throws Exception {
        SystemData.PhoneIMEI = PhoneUtils.getDeviceId(this);//获取手机标识，防止异常造成变量数据丢失
        SystemData.saleMan = dbUtils.findFirst(Selector.from(SaleManTable.class).orderBy("sid",true));
        if(SystemData.saleMan == null) return;//业务员数据为空值
        txtTitle.setText(SystemData.saleMan.gsmc);
        txtName.setText((SystemData.saleMan.RealName == null ? "你好" : SystemData.saleMan.RealName) + ",加油!");
        SystemData.SaleManID = SystemData.saleMan.id; //赋值业务员ID
        SystemData.SaleManPower = SystemData.saleMan.fcjgdqx * 0.01;//获取业务员的权限
        SystemData.SaleDeclare = SystemData.saleMan.ghsm;//购货声明
        SystemData.IsGoodsStockNotice = SystemData.saleMan.kcts;//是否库存提示
        SystemData.IsOperatorCustomer = SystemData.saleMan.khcz;//是否能操作客户信息
        SystemData.TimeToRecorder = SystemData.saleMan.dwjgsj<30?30:SystemData.saleMan.dwjgsj;//获取定位时间
        new com.lidroid.xutils.BitmapUtils(this).configDefaultLoadingImage(R.drawable.ic_plogin_face)
                .configDefaultLoadFailedImage(R.drawable.ic_plogin_face)
                .display(imgFace, SystemData.BASE_URL + SystemData.saleMan.Photo);//下载业务员头像
    }

    /**
     * 视图的点击事件
     * @param view
     */
    @OnClick(value = {R.id.plogin_txtSubmit, R.id.plogin_txtForgetPassowrd, R.id.plogin_txtSettings})
    public void OnViewClick(View view) {
        switch (view.getId()) {
            case R.id.plogin_txtSubmit://提交操作
                //处理登录问题
                dealDataDownloadOrSettings();//处理数据下载或数据设置
                break;
            case R.id.plogin_txtForgetPassowrd://忘记密码
                startActivity(new Intent(this, FindPwdActivity.class));
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.plogin_txtSettings://设置
                startActivity(new Intent(this, SoftwareSettingsActivity.class));
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
        }
    }

    /**
     * 处理数据下载或数据设置
     */
    public void dealDataDownloadOrSettings() {
        final ProgressDialog dialog =  ProgressDialog.show(this,"","加载中...");
        boolean isDownloadTable = isNeedDownloadNewData();//确定是否需要下载新的数据
        if (isDownloadTable) {//为真，开始下载数据
            if (!NetworkUtils.isNetAvailable(this)) {//网络不可用，数据不能下载
                Toast.makeText(this, "当前网络不可用，请检查您的链接地址是否正确?网络是否通畅?", Toast.LENGTH_SHORT).show();
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                return;
            }
            requestSignIn(dialog);//进行签到处理
        } else {//数据已经保存在本地
            String password = etPassword.getText().toString();
            try {
                if(SystemData.saleMan == null){
                    Toast.makeText(this, "当前无业务员数据，不能登录!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.equals((SystemData.saleMan.ssmm==null?"":SystemData.saleMan.ssmm))) {
                    if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                    SystemData.IsLogin = true;//登录成功
                    configer.edit().putString(PASSWORD_FIELD,password).commit();//纪录当前登录的密码
                    Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(this, MainActivity.class));
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                    this.finish();
                    return;
                } else {
                    Toast.makeText(this, "密码输入错误!", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(this, "登录异常!原因：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            if(dialog!=null && dialog.isShowing()) dialog.dismiss();
        }
    }

    /**
     * 是否需要下载新数据
     *
     * @return
     */
    public boolean isNeedDownloadNewData() {
        boolean isDownloadTable = false;
        if (configer.contains(DownloadTableActivity.DOWNLOAD_DATE_TIME)) {//如果包含时间键值
            String dateTime = configer.getString(DownloadTableActivity.DOWNLOAD_DATE_TIME, "");
            if(TextUtils.isEmpty(dateTime)) return true;
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                Date date = dateFormat.parse(dateTime);
                //比较日期数据，当记录的时间与现在的时间是否相等，不相等则需要下载数据，否则不需要下载数据
                if (date.compareTo(getTodayDate())!=0)
                    isDownloadTable = true;
            } catch (Exception e) {
                isDownloadTable = true;
                e.printStackTrace();
            }
        } else {//不包含时间键值
            isDownloadTable = true;
        }
        return isDownloadTable;
    }

    /**
     * 获取今天的日期数据
     *
     * @return
     */
    public Date getTodayDate() throws Exception {
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return new SimpleDateFormat("yyy/MM/dd").parse(year + "/" + month + "/" + day);
    }

    /**
     * 页面返回结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x001) {//下载数据的请求
            if (resultCode == RESULT_OK) {//请求下载数据成功,存储当前的时间记录
                try {
                    initSaleManInfo();//初始化客户数据
                } catch (Exception e) {
                    e.getMessage();
                    Toast.makeText(this, "初始化客户数据失败!", Toast.LENGTH_SHORT).show();
                    return;
                }
                configer.edit().putString(DownloadTableActivity.DOWNLOAD_DATE_TIME,
                        FormatUtils.standardDatetime(new Date(), "yyyy/MM/dd")).commit();
                Toast.makeText(this, "数据下载完成!请登录后使用!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "下载数据失败，请重新登录并下载!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 请求签到
     */
    public void requestSignIn(final ProgressDialog dialog) {
        String methodName = "Cx_QianDao";
        String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}";
        RequestParams params = new RequestParams("UTF-8");
        params.addBodyParameter("Method", methodName);
        params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
        System.out.println("========请求签到加密后的字符串：" + MD5Utils.getMd5(methodName + messageBody + "19491001") + "=================");
        params.addBodyParameter("MessageBody",                                                                                                                                                                                                                                                                                                                                                                                                                                                                               "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}");
        new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                .send(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> str) {
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                System.out.println("签到结果是：----->" + str.result);
                try {
                    BaseResultModel resultModel = new Gson().fromJson(str.result, BaseResultModel.class);
                    if (resultModel != null && (resultModel.Result.equals("0000") || resultModel.Result.equals("0005"))) {
                        if (resultModel.Result.equals("0000")) {
                            Toast.makeText(LoginActivity.this, "签到成功!", Toast.LENGTH_SHORT).show();
                        }
                        //运行数据下载页面
                        startActivityForResult(new Intent(LoginActivity.this, DownloadTableActivity.class), 0x001);
                        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                    } else {
                        Toast.makeText(LoginActivity.this, "签到失败!原因：" + resultModel.Message, Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this,"操作失败!原因："+e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                Toast.makeText(LoginActivity.this, "网络错误，请检查您当前的网络是否可用!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try{initSaleManInfo();}catch (Exception e){e.printStackTrace();}//初始化用户信息
    }

    /**
     * 退出程序
     */
    public void goBack(){
        if(dbUtils!=null) dbUtils = null;//释放数据库操作对象
        stopService(new Intent(this, LocationService.class));
        stopService(new Intent(this, ForegroundService.class));
        this.finish();
        android.os.Process.killProcess(android.os.Process.myPid());
        android.os.Process.killProcess(android.os.Process.myTid());
        android.os.Process.killProcess(android.os.Process.myUid());
        System.exit(0);
    }

    private long exitTime = 0;//退出的时间戳

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
            long nowTime = System.currentTimeMillis();
            if(nowTime-exitTime>800){
                exitTime = nowTime;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                return true;
            }
            goBack();//退出程序
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        if(exitAppReceiver!=null){
            this.unregisterReceiver(exitAppReceiver);
        }
        super.onDestroy();
    }

}
